package com.tongcao.cn.util;


import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Author Booker
 * @Description
 * @Date 2018/3/21 14:41
 */
public class RequestUtils {

    public static final String EQUALS = "=";
    public static final String AND = "&";


    /**
     * 拼接requestMap参数信息
     *
     * @param request
     * @return
     */
    public static String parseRequestMapToStr(HttpServletRequest request) {
        return parseRequestMapToStr((HttpServletRequest) request.getParameterMap());
    }

    /**
     * 拼接requestMap参数信息
     *
     * @param map
     * @return
     */
    public static String parseRequestMapToStr(Map<Object, Object> map) {
        StringBuilder sb = new StringBuilder();
        if (CollectionUtils.isEmpty(map)) {
            return sb.toString();
        }
        sb.append("?");
        for (Map.Entry<Object, Object> entry : map.entrySet()) {
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            sb.append(key).append(EQUALS).append(value).append(AND);
        }
        return sb.substring(0, sb.length() - 1).toString();
    }

    /**
     * @param request
     * @param key
     * @return
     */
    public static String getValue(HttpServletRequest request, String key) {
        return getValue(request, key, null);
    }


    /**
     * @param request
     * @param key
     * @return
     */
    public static String getValue(HttpServletRequest request, String key, String defaultValue) {
        String value = request.getParameter(key);
        return value == null ? defaultValue : value;
    }

    /**
     * 获取请求上下文
     *
     * @return
     */
    public static HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }
}
